const Koa = require('koa')
const expressJoi = require('@escook/express-joi');
const joi = require('joi');
const homeRoutes = require('../routes/')
const aHomeRoutes = require('../routes/home')
const userRouter = require('../routes/user')
const wechatRouter = require('../routes/wechat')
const chatgptRouter = require('../routes/chatgpt')
const dyRouter = require('../routes/dy');
const wallpaperRouter = require('../routes/wallpaper');
const utilsRouter = require('../routes/utils');
const youtubeRouter = require('../routes/youtube');
const { expressjwt: jwt } = require('express-jwt');
const { SECRET_KEY } = require('../config');
const https = require('https');
const express = require('express');
const { createServer } = require("http");
const { Server } = require("socket.io");
const cors = require("cors");
const fs = require('fs');

// 读取证书和私钥
const options = {
    key: fs.readFileSync('./private.key'), // 私钥
    cert: fs.readFileSync('./certificate.crt') // 证书
};


// const app = new Koa()
const app = express();
const httpServer = https.createServer(options, app)
const io = new Server(httpServer, {});

// homeRoutes(app)
// app.use(aHomeRoutes.routes())
// app.use(aHomeRoutes.allowedMethods())

app.use(express.json())
app.use(express.urlencoded({ extended: false }));
app.use(cors());

app.use(jwt({
    secret: SECRET_KEY,
    algorithms: ['HS256']
}).unless({
    path: [/^\/user\/register/, /^\/user\/login/, /^\/user\/verification-code/, /^\/user\/problem\/addcount/,
        /^\/dy\/*/, /^\/api\/*/, /^\/chatgpt\/api\/v1\/*/, /^\/wx\/*/, /^\/chatgpt\/ai-chat\/*/,
        /^\/utils\/*/, /^\/wp\/*/, /^\/ytl\/*/]
}));

app.use('/user', userRouter);
app.use('/wechat', wechatRouter);
app.use('/wx', wechatRouter);
app.use('/chatgpt', chatgptRouter);
app.use('/dy', dyRouter);
app.use('/api', wallpaperRouter);
app.use('/utils', utilsRouter);
app.use('/ytl', youtubeRouter);

// 壁纸接口
app.use('/wp', wallpaperRouter);

app.use((err, req, res, next) => {
    if (err instanceof joi.ValidationError) {
        return res.send({
            status: 400,
            msg: err.details[0].message
        });
        // return res.status(400).send(err.details[0].message)
    } else if (err.name == 'UnauthorizedError') {
        return res.send({
            status: 401,
            msg: '无效的token！'
        });
    } else if (res.headersSent) {
        return next(err);
    }
    console.log('err:', err);
    // res.send({
    //     status: 500,
    //     msg: err.message
    // })
    // next()
})

// io.on('connection', (socket) => {
//     socket.on('message', (data) => {
//         io.emit('message', data);
//     })
// })
// httpServer.listen(8688);

module.exports = httpServer